package manage.shiro;

import entity.Admin;
import manage.service.AdminService;
import manage.utils.MyByteSource;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;
import java.util.Set;

public class AdminRealm extends AuthorizingRealm {

    @Autowired
    private AdminService adminService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //System.out.println("开始授权...");
        Admin admin = (Admin) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //查询该管理员下的所有角色以及权限
        Integer id = admin.getId();
        if (admin.getType() == 0) {
            //如果是超级管理员拥有所有的权限
            authorizationInfo.addStringPermission("*:*");
        } else {
            Set<String> perms = adminService.queryPermsByAdminId(id);
            perms.removeAll(Collections.singleton(null));
            perms.removeAll(Collections.singleton(""));
            System.out.println(perms);
            authorizationInfo.setStringPermissions(perms);
        }
        return authorizationInfo;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //System.out.println("进行认证...");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        Admin admin = adminService.login(token.getUsername());
        if (admin == null){
            //return null;
            throw new UnknownAccountException("用户名或密码错误...");
        }
        if (admin.getAvailable() != 1){
            throw new LockedAccountException("该账户被锁定了,请联系管理员解锁...");
        }
        MyByteSource salt = new MyByteSource(admin.getSalt());
        return new SimpleAuthenticationInfo(admin, admin.getPassword(),salt ,getName());
    }
}
